﻿using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

using My.ELibrary.Model.Search;
using My.ELibrary.Business.Search;

public partial class Search_Default : System.Web.UI.Page
{

    private string SearchType
    {
        get
        {
            if (Request["SearchType"] != null)
            {
                return Request["SearchType"].ToString();
            }
            return string.Empty;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (SearchType != string.Empty)
            {
                radioSearchType.Visible = false;
                radioSearchType.SelectedIndex = -1;
                btnSearch_Click(null, null);
            }
        }
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        string strValue = "";
        IList<SearchResultModel> lstRes = null;
        if (SearchType != string.Empty)
        {
            strValue = SearchType;
            lstRes = SearchMainBLL.GetInstance().getSearchResult(null, strValue);
        }
        else
        {
            strValue = radioSearchType.SelectedValue;
            string strContent = txtSearch.Text.Trim().Replace("'", "''");
            lstRes = SearchMainBLL.GetInstance().getSearchResult(strContent, strValue);
        }

        BindResult(lstRes);
    }

    private void BindResult(IList<SearchResultModel> lstRes)
    {
        StringBuilder sbDivContent = new StringBuilder();
        foreach(SearchResultModel resModel in lstRes)
        {
            sbDivContent.Append(getResHtml(resModel));
        }

        divSearchResult.InnerHtml = sbDivContent.ToString();

    }

    private string getResHtml(SearchResultModel resModel)
    {
        if (resModel == null)
            return string.Empty;
        StringBuilder sbHtml = new StringBuilder();

        string strLink = "ShowResult.aspx?ModelType=" + resModel.ModelType.ToString() + "&ModelId=" + resModel.Link;

        sbHtml.Append("<table width=\"100%\">");
        sbHtml.AppendFormat("<tr><td><a href={0}>{1}</a></td></tr>", strLink, resModel.Title);
        sbHtml.AppendFormat("<tr><td>{0}</td></tr>",resModel.CommonContent);
        sbHtml.AppendFormat("</table>");

        return sbHtml.ToString();
    }
}
